package com.playcrab.adouban;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.ContextMenu;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.webkit.WebView;
import android.widget.AbsListView;
import android.widget.ArrayAdapter;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AbsListView.OnScrollListener;
import android.widget.AdapterView.AdapterContextMenuInfo;

import com.google.gdata.client.douban.DoubanService;
import com.google.gdata.data.douban.Attribute;
import com.google.gdata.data.douban.CollectionEntry;
import com.google.gdata.data.douban.CollectionFeed;
import com.google.gdata.data.douban.Subject;
import com.google.gdata.util.ServiceException;

public class CollectionList extends  BaseActivity {
	private static final int COUNT_ITEMS_PER_PAGE = 10;
	private static final String LOG_TAG = "CollectionList";

	private ListView collectionList;
	private ProgressDialog progressDialog = null;
	CollectionListAdapter collectionListAdapter = null;
	private Handler handler = new Handler();
	String query;
	String type;
	CollectionFeed feed;
	List<CollectionEntry> collections;
    public List<CollectionEntry> getCollections() {
		return collections;
	}

	public void setCollections(List<CollectionEntry> collections) {
		this.collections = collections;
	}

	int currentStartIndex = 1;
	
	private static final int MENU_SEARCH = Menu.FIRST + 1;
	private static final int MENU_SCAN = Menu.FIRST + 2; 
	
	
	public static final int MENU_RETURN = Menu.FIRST + 10;

	public static final int MENU_REPLY = Menu.FIRST + 7;
	public static final int MENU_DELETE = Menu.FIRST + 8;
	private static final int MENU_VIEW_SUBJECT = Menu.FIRST + 100;
	private static final int MENU_VIEW_MDOUBAN = Menu.FIRST + 101;
	private static final int MENU_VIEW_DOUBAN = Menu.FIRST + 102;
	private static final int MENU_REFRESH =  Menu.FIRST + 103;
	private static final int MENU_EXIT =  Menu.FIRST + 104;
	
	

	

	public class CollectionListAdapter extends AutoRefreshAdapter<CollectionEntry> {

		private static final String LOG_TAG = "CollectionListAdapter";
		Activity context;
		LayoutInflater inflater;
		WebView userIcon;
		TextView username, replyTo, updateBody, via, timestamp;
		List<CollectionEntry> more_cols;

		public CollectionListAdapter(Activity context, List<CollectionEntry> collections) {
			super(context, collections);
			inflater = LayoutInflater.from(context);

			this.context = context;
			this.itemList = collections;
			// TODO Auto-generated constructor stub
		}

		public String getCollectionInfo(CollectionEntry se) { 
			 Subject s = se.getSubjectEntry();
			if (CollectionList.this.type.equals("book") ) {
				return getBookInfo(s);
			} else if (CollectionList.this.type.equals("movie")) {
				return getMovieInfo(s);
			} else if (CollectionList.this.type.equals("music")) {
				return getMusicInfo(s);
			} else {
				return "error";
			}
		}

		public String getMusicInfo(Subject se) {
			List<Attribute> attrs = se.getAttributes();
			List<String> strs = new ArrayList();
			for (int i = 0; i < attrs.size() && strs.size() < 4; i++) {
				Attribute attr = attrs.get(i);
				String name = attr.getName();
				if (name.equals("singer") || name.equals("publisher")) {
					strs.add(attr.getContent());
				}
			}
			String info = "";
			for (int j = 0; j < strs.size(); j++) {
				info = info.concat(strs.get(j));
				if (j != strs.size() - 1) {
					info = info.concat(" / ");
				}
			}
			return info;
		}

		public String getMovieInfo(Subject se) {
			String author = null;
			if (se.getAuthors().size() > 0) {
				author = se.getAuthors().get(0).getName();
			}

			List<Attribute> attrs = se.getAttributes();
			List<String> strs = new ArrayList();
			for (int i = 0; i < attrs.size() && strs.size() < 4; i++) {
				Attribute attr = attrs.get(i);
				String name = attr.getName();
				if (name.equals("cast")) {
					strs.add(attr.getContent());
				}
			}
			String info = "";
			for (int j = 0; j < strs.size(); j++) {
				info = info.concat(strs.get(j));
				if (j != strs.size() - 1) {
					info = info.concat(" / ");
				}
			}
			if (author != null) {
				String info1 = info;
				info = author.concat(" / ");
				if (!info1.equals(""))
					info = info.concat(info1);
			}
			return info;
		}

		public String getBookInfo(Subject se) {
			String author = "", publisher = "", pubdate = "";
			List<Attribute> attrs = se.getAttributes();
			List<String> strs = new ArrayList();
			for (int i = 0; i < attrs.size() && strs.size() < 4; i++) {
				Attribute attr = attrs.get(i);
				String name = attr.getName();
				if (name.equals("author") || name.equals("publisher")
						|| name.equals("pubdate")) {
					strs.add(attr.getContent());
				}
			}
			String info = "";
			for (int j = 0; j < strs.size(); j++) {
				info = info.concat(strs.get(j));
				if (j != strs.size() - 1) {
					info = info.concat(" / ");
				}
			}
			return info;
		}
		
		@Override
		public View getItemView(int position) {
			View row = inflater.inflate(R.layout.collection_row, null);
			row.setLongClickable(true);
			row.setClickable(true);
			
			final CollectionEntry se = itemList.get(position);

			row.setOnClickListener(new OnClickListener(){ 
				@Override
				public void onClick(View arg0) {
					// TODO Auto-generated method stub 
		        		String sid = se.getSubjectEntry().getId().substring(se.getSubjectEntry().getId().lastIndexOf('/')+1);
		        		Intent i = new Intent(CollectionList.this, ViewSubject.getViewClass(CollectionList.this.type)); 
						i.putExtra("id", sid );
						i.putExtra("type", type );
						startActivity(i);  
				}
				
			});
			 
			row.setTag(se);
			if (se == null) {
				return row;
			}

			if (se.getSubjectEntry().getLink("image", null) != null) {
				WebView collection_image = (WebView) row
						.findViewById(R.id.collection_image);
				collection_image.loadUrl(se.getSubjectEntry().getLink("image", null).getHref());
			}
			if (se.getTitle() != null) {
				TextView collection_title = (TextView) row
						.findViewById(R.id.collection_title);
				collection_title.setText(se.getTitle().getPlainText());
			}
			TextView collection_info = (TextView) row.findViewById(R.id.collection_info);

			collection_info.setText(this.getCollectionInfo(se));

			return row;

		}

		public void addCollections(List<CollectionEntry> subs) {
			// TODO Auto-generated method stub
			itemList.addAll(itemList.size(), subs);
			notifyDataSetChanged();
		}
 
		protected boolean cacheInBackground() {
			more_cols = CollectionList.this.updateCollections();
			
			return(more_cols.size() == CollectionList.COUNT_ITEMS_PER_PAGE);
		}
		
		protected void appendCachedData() {
			addCollections(more_cols);
		}

	}
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.collection_list);

		Bundle bundle = this.getIntent().getExtras();
		query = bundle.getString("q");
		type = bundle.getString("type");
		Log.v(LOG_TAG, "query:" + query);

		collectionList =   (ListView) findViewById(R.id.collection_list);
		   
		
		registerForContextMenu(collectionList);
		
		collectionListAdapter = new CollectionListAdapter(
				CollectionList.this, new ArrayList<CollectionEntry>());
		collectionList.setAdapter(collectionListAdapter); 		
		

//		progressDialog = ProgressDialog.show(CollectionList.this, CollectionList.this.getResources().getText(R.string.waiting),
//				CollectionList.this.getResources().getText(R.string.searching), true);
//
//		new Thread() {
//			public void run() { 
// 				collections =updateCollections();
// 				progressDialog.dismiss();
//				handler.post(new Runnable() {
//					public void run() {
//						collectionListAdapter = new CollectionListAdapter(
//								CollectionList.this, collections);
//						collectionList.setAdapter(collectionListAdapter); 				
//					}
//				}); 
//
//			}
//		}.start();

		InsertPanel();
	} 
	
	public void refreshCollections(){
		if (this.collectionListAdapter == null
				|| this.collectionListAdapter.itemList == null)
			return ;
		Toast.makeText(
				getApplicationContext(),
				this.getResources().getText(
						R.string.waiting),
				Toast.LENGTH_SHORT).show();
 
		new Thread() {
			public void run() { 
				collections = updateCollections(1);  
				CollectionList.this.collectionListAdapter.itemList.clear();
				CollectionList.this.collectionListAdapter.itemList.addAll(collections); 
				handler.post(new Runnable() {
					public void run() {
						CollectionList.this.collectionListAdapter.notifyDataSetChanged();
					}
				});
			 
			}
		}.start(); 
		 
	}
	
	protected List<CollectionEntry> updateCollections(int startIndex) {
		currentStartIndex = startIndex;
		 
		String userId = getStoredUserId();
		DoubanService service = getAuthedDoubanService();//DoubanAPI.getInstance().getService();
		if(service == null){
			return new ArrayList();
		}
		try {
			feed = service.getUserCollections(userId, type, null, null, CollectionList.this.currentStartIndex, COUNT_ITEMS_PER_PAGE);
			
			collections = feed.getEntries();
			return  collections;

		} catch (IOException e) { 
			e.printStackTrace(); 
			this.showInfo(getString(R.string.network_error));
		} catch (ServiceException e) {
			e.printStackTrace();
			this.showInfo(getString(R.string.service_error));
		} finally {
		}
		return new ArrayList();
	}
    
	protected List<CollectionEntry> updateCollections() {
		int currentStartIndex = 1;
		if(this.collectionListAdapter == null || this.collectionListAdapter.itemList == null)
			currentStartIndex = 1;
		else
			currentStartIndex = this.collectionListAdapter.itemList.size()+1;
		return updateCollections(currentStartIndex);
	}

	@Override
	public void onCreateContextMenu(ContextMenu menu, View v,
			ContextMenu.ContextMenuInfo menuInfo) {
		menu.setHeaderTitle("操作菜单");
		AdapterContextMenuInfo info = (AdapterContextMenuInfo) menuInfo;
		menu.add(0, MENU_VIEW_SUBJECT, 0, "查看");
		menu.add(0, MENU_VIEW_MDOUBAN, 0, "在手机豆瓣中打开");
		menu.add(0, MENU_VIEW_DOUBAN, 0, "在豆瓣网中打开");

	}
	
	
    @Override 
    public boolean onContextItemSelected(MenuItem item) {
        AdapterContextMenuInfo info = (AdapterContextMenuInfo) item.getMenuInfo();
		CollectionEntry se = this.collectionListAdapter.itemList.get(info.position);
		String id = se.getSubjectEntry().getId().substring(se.getSubjectEntry().getId().lastIndexOf('/')+1); 
        switch (item.getItemId()) {
			case MENU_VIEW_SUBJECT: {
				Intent i = new Intent(this, ViewSubject.getViewClass(type)); 
				i.putExtra("id", id );
				i.putExtra("type", type );
				startActivity(i);
				return true;
			}
			case MENU_VIEW_MDOUBAN:{
				String url = "http://m.douban.com/".concat(type).concat("/subject/").concat(id).concat("/"); 
				Intent openBrowserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(url)); 
				startActivity(openBrowserIntent);  
				return true;
						  
			}
			case MENU_VIEW_DOUBAN:{
				String url = "http://www.douban.com/subject/".concat(id).concat("/"); 
				Intent openBrowserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(url)); 
				startActivity(openBrowserIntent);  
				return true;
						  
			}

        }
		return super.onOptionsItemSelected(item);
        
    }

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
			case MENU_SEARCH: {
				Intent intent = new Intent(CollectionList.this, Main.class);
				startActivity(intent);
				return true;
			}
			case MENU_SCAN:{
				Intent intent = new Intent(CollectionList.this, Main.class);
				intent.putExtra("event", "scan" );
				startActivity(intent);
				return true;
			}
			case MENU_EXIT:{
				this.finish();
				return true;
				
			}case MENU_REFRESH:{
				this.refreshCollections();
				return true;
			}
				

		}
		return super.onOptionsItemSelected(item);
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		super.onCreateOptionsMenu(menu);
		menu.add(0, MENU_REFRESH, 0, "刷新").setIcon(android.R.drawable.ic_menu_rotate)
		.setAlphabeticShortcut('R'); 
		menu.add(0, MENU_EXIT, 0, "返回").setIcon(android.R.drawable.ic_menu_close_clear_cancel)
				.setAlphabeticShortcut('X'); 
		return true;
	}
	
	
	
}
